<template>
  <el-upload
    class="upload-demo"
    :action="path"
    :headers="headers"
    :data="datas"
    :on-success="success"
    multiple
    :show-file-list="false"
    :limit="maxLimit"
    :on-exceed="handleExceed"
    :file-list="fileList"
  >
    <slot>
      <el-button size="small" type="warning">点击上传</el-button>
    </slot>
  </el-upload>
</template>

<script>
export default {
  props: {
    maxLimit: {
      type: Number,
      default: 1
    },
    type: {
      type: Number,
      default: 1 // 1没有额外参数除了1以外其他参数跟后端自己约定
    },
    parameter: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      // eslint-disable-next-line no-undef
      path: `${GLObconfig.baseURL}/file`,
      fileList: [],
      headers: {
        Authorization: 'Bearer ' + this.$store.state.getter.token
      }
    }
  },
  computed: {
    datas() {
      return {
        type: this.type,
        data: JSON.stringify(this.parameter)
      }
    }
  },
  methods: {
    // 上传成功
    success(response, file, fileList) {
      if (response.status) {
        this.$emit('success', fileList)
        this.$message({ message: '上传成功', type: 'success' })
        this.fileList = []
      } else {
        this.$message({ message: response.message, type: 'warning' })
        this.fileList = []
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 ${this.maxLimit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    }
  }
}
</script>

<style scoped>

</style>
